#!groovy
import groovy.json.JsonOutput
import groovy.json.JsonSlurper


node ("sftp-artifacts"){
    def sftpUrl = params.sftpUrl
    def nexusHost = params.nexusHost
    def app = params.app
    def tag = params.tag
    def packageName = params.packageName
    def packageType = params.packageType
    try{
        println("App :"+ app +" Tag: "+tag)
        wrap([$class: 'MaskPasswordsBuildWrapper',
              varPasswordPairs: [[password: "${params.sftpUser}", var: 'sftpUser'],
                                 [password: "${params.sftpPwd}", var: 'sftpPwd'],
                                 [password: "${params.releasePwd}", var: 'releasePwd']]]){
            downloadFromSftp(app,packageName, tag,sftpUrl,packageType)
            publishToNexus(app,packageName,nexusHost)
            //SFTP拉取成功
            notifyDeployCentral(30001)
        }
    }catch (e){
        echo 'Pull Artifact error !'
        //SFTP拉取失败
        notifyDeployCentral(30002)
        throw exc
    }
}

def downloadFromSftp(app,packageName,tag,sftpUrl,packageType){
    stage('Pull Artifact From SFTP') {
        echo " Pull Artifact ${app}-${packageName}-${tag}.${packageType} "
        script{
            withEnv(['JENKINS_NODE_COOKIE=dontkillme']) {
                sh """
                lftp -u ${params.sftpUser},${params.sftpPwd} $sftpUrl <<EOF
                # the next 3 lines put you in ftpes mode. Uncomment if you are having trouble connecting.
                # set ftp:ssl-force true
                # set ftp:ssl-protect-data true
                # set ssl:verify-certificate no
                # transfer starts now...
                get -c /file/${app}/${tag}/${packageName}.${packageType}.tar.gz
                exit
                EOF
                echo "----- Transfer finished -----"
            """
            }
        }
    }
}

def publishToNexus(appName,packageName,nexusHost) {
    stage ('Release App') {
        script{
            withEnv(['JENKINS_NODE_COOKIE=dontkillme']) {
                sh """
                openssl des3 -d -k ${params.releasePwd} -salt -in ${packageName}.${packageType}.tar.gz | tar xzf -
                echo "----- release tar finished -----"
                rm -rf ${packageName}.${packageType}.tar.gz
                ls
                echo "----- rm -rf ${packageName}.${packageType}.tar.gz -----"
            """
            }
        }
    }
    stage ('Nexus Deploy') {
        sh """
          curl --request DELETE --user "admin:admin123" ${params.nexusRepos}/${params.app}/${params.tag}/${params.app}-${params.tag}.${params.packageType}
          """
        nexusArtifactUploader(
                artifacts: [
                [artifactId: "${appName}",
                 classifier: "",
                 file: "${packageName}.${params.packageType}",
                 type: "${params.packageType}"],
                ],
                credentialsId: "nexus",
                groupId: "com.fbank",
                nexusUrl: "${nexusHost}",
                nexusVersion: 'nexus2',
                protocol: "http",
                repository: "releases",
                version: "${params.tag}"
        )
        script{
            withEnv(['JENKINS_NODE_COOKIE=dontkillme']) {
                sh """
                    rm -rf ${packageName}.${packageType}
                    echo "----- rm -rf ${packageName}.${packageType} -----"
                """
            }
        }
    }
}

def notifyDeployCentral(status){
    stage("Notify DeployCentral"){
        echo "Notify DeployCentral: "+status
        def response = httpRequest(url:"${params.callBackHost}/deploy-central/prod/jenkins/notify?callBackId=${params.callBackId}&status=${status}&buildId=${BUILD_ID}&action=${JOB_NAME}",timeout: 10)
        println('Status: '+response.status)
    }
}